package com.yuhf.db.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DBConnection {

	private static Logger log=Logger.getLogger(DBConnection.class);
	
	private static ThreadLocal<Connection> connections=new ThreadLocal<>();
	
	private static final String DRIVER_CLASS_NAME;
	private static final String URL;
	private static final String NAME;
	private static final String PASSWORD;
	static {
		Properties prop=new Properties();
		try {
			prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
		} catch (IOException e) {
			log.error("jdbc.properties file not found,the exception is:"+e.getLocalizedMessage());
		}
		DRIVER_CLASS_NAME=prop.getProperty("jdbc.driverClassName");
		URL=prop.getProperty("jdbc.url");
		NAME=prop.getProperty("jdbc.name");
		PASSWORD=prop.getProperty("jdbc.password");
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			log.error("class not found,the exception is:"+e.getLocalizedMessage());
		}
	}
	public static Connection getConnection() {
		Connection connection=connections.get();
		try {
			if(connection==null||connection.isClosed()) {
				try {
					connection=DriverManager.getConnection(URL,NAME,PASSWORD);
					log.debug("open connection success...");
					connections.set(connection);
				} catch (SQLException e) {
					log.error("database connection error,the exception is:"+e.getLocalizedMessage());
				}			
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		log.debug("get connection...");
		return connection;
	}
	public static void closeConnection(Connection connection) {
		if(connection!=null) {
			try {
				connection.close();
				log.debug("close connection success...");
			} catch (SQLException e) {
				log.error("database close error,the exception is:"+e.getLocalizedMessage());
			}
		}
	}
}
